package com.sn.seabattle;

import java.io.IOException;
import java.util.UUID;

import android.annotation.TargetApi;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.widget.Toast;

@TargetApi(5)
public class BluetoothService extends Thread {
    private BluetoothSocket s;
    private BluetoothServerSocket ss;
    private BluetoothDevice device;
    private Handler mHandler;
    private boolean isServer;
    private BluetoothAdapter BTA;

    public BluetoothService(BluetoothAdapter BTA, BluetoothDevice d,
            Handler handler, boolean isServer) {
        this.BTA = BTA;
        this.isServer=isServer;
        mHandler = handler;
        device = d;
        if (isServer) {
            BluetoothServerSocket stmp = null;
            try {
                stmp = BTA
                        .listenUsingRfcommWithServiceRecord(
                                "SeaBattle",
                                UUID.fromString("fa87c0d0-afac-11de-8888-0800200c9a66"));
            } catch (IOException e) {
            }
            ss = stmp;

        } else {
            try {
                BluetoothSocket tmp = null;
                tmp = device.createRfcommSocketToServiceRecord(UUID
                        .fromString("fa87c0d0-afac-11de-8888-0800200c9a66"));
                s = tmp;
            } catch (IOException e) {
            }
        }
        start();
    }

    public void run() {
        BTA.cancelDiscovery();
        if(isServer){
            try {
                report(1, "waiting");
                s = ss.accept();
                report(1, "connected");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
        try {
            report(1, "connecting");
            s.connect();
            report(1, "connect!");
        } catch (IOException e) {
        }}
    }

    private void report(int m, String s) {
        Message msg = mHandler.obtainMessage(m);
        switch (m) {
        case 1:
            Bundle b = new Bundle();
            b.putString("message", s);
            msg.setData(b);
            break;
        }

        mHandler.sendMessage(msg);
    }
}
